<template>
    <div id="editor-container">
        <!-- 语言切换下拉框 -->
        <select v-model="selectedLang" class="lang-selector">
            <option value="java">Java</option>
            <option value="javascript">JavaScript</option>
        </select>

        <!-- CodeMirror 编辑器 -->
        <codemirror v-model="code" style="height: 100%;" :autofocus="true" :extensions="extensions" />
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watchEffect } from 'vue'
import { Codemirror } from 'vue-codemirror'
import { java } from '@codemirror/lang-java'
import { javascript } from '@codemirror/lang-javascript' // 新增 JS 支持
import { oneDark } from "@codemirror/theme-one-dark"


// 代码内容
const code = ref<string>(`// 选择上方的语言切换
  public class HelloWorld {
      public static void main(String[] args) {
          System.out.println("Hello Java!");
      }
  }`)

// 语言选择
const selectedLang = ref<'java' | 'javascript'>('java')

// 动态计算扩展
const extensions = computed(() => {
    const langExtension = selectedLang.value === 'java'
        ? java()
        : javascript()
    return [langExtension, oneDark]
})

// 接收父组件传来的事件函数
const emits = defineEmits(["codeInput"]);
const props = defineProps(["codeTemplate"]);

// 监听父组件的数据传递
watchEffect(()=>{
    code.value = props.codeTemplate;
});

// 监听code值的改变
watchEffect(() => {
    if(code.value){
        // 用户输入代码时，触发父组件注册的回调函数
        emits("codeInput",code.value);
    }
});




</script>

<style scoped>
#editor-container {
    height: 430px;
    /* 设置固定高度或根据父容器调整 */
    position: relative;
}

.lang-selector {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 999;
    padding: 6px 12px;
    border: 1px solid #434C5E;
    border-radius: 4px;
    background: #282C34;
    color: #ABB2BF;
    outline: none;
    cursor: pointer;
}

/* 优化编辑器样式 */
:deep(.cm-editor) {
    height: 100%;
    font-size: 14px;
    border-radius: 8px;
    overflow: hidden;
}

:deep(.cm-scroller) {
    font-family: 'Fira Code', monospace;
}
</style>